import { NavigationGuardNext, RouteLocationNormalized } from "vue-router";
import { Helper } from "../helper/helper.service";
import { useAclHooks } from "../pinia/store/acl.store";
import { useMenuHooks } from "../pinia/store/menu.store";
import { useSettingHooks } from "../pinia/store/setting.store";
import { BaseRouter } from "./base";
import { CacheService } from "../cache/cache.service";

export class RouterService extends BaseRouter {
  private static router: RouterService;
  private whiteList = ["/error/403", "/error/404"];
  static of() {
    if (!RouterService.router) {
      RouterService.router = new RouterService();
    }
    return RouterService.router;
  }

  isLogin(path: string) {
    return path === "/login";
  }

  beforeEvent(
    _to: RouteLocationNormalized,
    _from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) {
    const setting = useSettingHooks();
    const acl = useAclHooks();
    const menu = useMenuHooks();
    const token = CacheService.of().getToken();
    /** 路由缓存设置 */
    if (_to.meta?.keepAlive) {
      setting.handleAliveRoute(_to, "add");
      /** 页面整体刷新和点击标签页刷新 */
      if (_from.name === undefined || _from.name === "Redirect") {
        setting.handleAliveRoute(_to);
      }
    }
    /** 在路由跳转前先销毁静态弹出层 */
    Helper.destoryModel();
    /** 设置页面标题 */
    _to.matched.some(item => {
      if (!item.meta.title) return "";
      const prefix = setting.getPrefix;
      if (prefix) document.title = ` ${prefix} | ${item.meta.title} `;
      else document.title = item.meta.title as string;
    });
    /** 权限判断 */
    if (this.whiteList.includes(_to.path)) {
      next();
    } else if (!token && !this.isLogin(_to.path)) {
      next({ path: `/login` });
    } else if (!this.router.hasRoute(_to.name) && !this.isLogin(_to.path)) {
      if (token) {
        next({ path: menu.getDefaultActive.router });
      } else {
        next({ path: "/error/404" });
      }
    } else if (this.isLogin(_to.path)) {
      if (token) {
        next({ path: _from?.path || menu.getDefaultActive.router });
      } else {
        next();
      }
    } else if (!acl.hasMenuAcl("get", _to.path.replace("/redirect", ""))) {
      next({ path: "/error/403" });
    } else {
      next();
    }
  }

  afterEvent() {
    console.log("to, _fromto, _fromto, _from");
  }
}
